"""证照管理"""

from datetime import timedelta

from odoo import models, api, fields
from odoo.tools import float_compare
from odoo.exceptions import UserError, ValidationError


"""证照管理部分，分为证照模板和限制规则。证照模板目前看来只是记录客户的经营范围。而限制规则则是体现当拥有某种
证照时需要应用的某种限制"""

GRANT_TYPE = [('product_categ', '商品分类'), ('dosage', '剂型'), ('instrument', '医疗器械分类'), ('product', '产品')]


class GSPLicense(models.Model):
    _name = 'gsp.license'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _description = '客户证照'

    partner_id = fields.Many2one('res.partner', string="所属合作伙伴")
    template_id = fields.Many2one('gsp.license.template', string="证照名称", required=True)
    grant_type = fields.Selection(related="template_id.grant_type", store=True, string="授权类型",)
    license_num = fields.Char('证照编号')
    issue_org = fields.Char('发行机关')
    issue_date = fields.Date('发行日期')
    expire_date = fields.Date('有效期至')
    product_categ_ids = fields.Many2many('gsp.product.categ', string="商品分类", domain=[('can_use', '=', True)])
    product_ids = fields.Many2many('product.product', string="产品")
    dosage_ids = fields.Many2many('gsp.dosage.categ', string="剂型")
    instrument_categ_ids = fields.Many2many('gsp.instrument.categ', string="医疗器械分类")

    @api.model
    def expiration_check(self):
        """检查证照是否到期，并提醒指定用户，TODO 时区检查？"""
        today = fields.Date.today()
        remind_days = self.env.user.company_id.remind_days
        check_date = today + timedelta(days=remind_days)
        expiring_license_ids = self.env['gsp.license'].sudo().search([
                ('expire_date', '<=', check_date)])
        self._notify_user(expiring_license_ids)

    def _notify_user(self, license_ids):
        """提醒用户"""
        uses_ids = self._get_notified_users()
        partner_ids = uses_ids.mapped('partner_id.id')
        subject = '证照到期提醒'
        odoobot_id = self.env['ir.model.data'].xmlid_to_res_id("base.partner_root")
        for l in license_ids:
            license_name = l.template_id and l.template_id.name or ""
            k = l.partner_id.message_post(partner_ids=partner_ids,
                              body=f"证照“{license_name}”将于“{l.expire_date}”到期，请关注！",
                               # message_type='sms',
                               subject=subject,
                               author_id=odoobot_id,
                               # notified_partner_ids=[(6, 0, partner_ids.ids)],
                               notification_ids=[(0, 0, {
                                   'res_partner_id': p_id,
                                   # 'mail_id': mail.id,
                                   'notification_type': 'inbox',
                                   'is_read': False,
                                   'is_mail': False,
                                   # 'notification_status': 'sent',
                               }) for p_id in partner_ids]
                               )

        return

    def _get_notified_users(self):
        """获取需要接收证照到期提醒的用户"""
        return self.env.ref('nd_gsp.gsp_license_notify_receiver').sudo().users


class GrantLicense(models.Model):
    _name = 'gsp.grant'
    _description = '授权委托书'

    partner_id = fields.Many2one('res.partner', string="所属合作伙伴")
    grant_type = fields.Selection(GRANT_TYPE, string="授权类型",)
    user_id = fields.Char(string="销售员")
    num = fields.Char('身份证号')
    start = fields.Date('授权开始日期')
    end = fields.Date('授权结束日期')
    area = fields.Char('授权地域')
    product_categ_ids = fields.Many2many('gsp.product.categ', string="授权商品分类", domain=[('can_use', '=', True)])
    dosage_ids = fields.Many2many('gsp.dosage.categ', string="授权剂型")


class LicenseTemplate(models.Model):
    _name = 'gsp.license.template'
    _inherit = ['gsp.base', 'nd.base']
    _description = '证照模板'

    grant_type = fields.Selection(GRANT_TYPE, string="授权类型", readonly=True,
                                  states={'draft': [('readonly', False)]}, track_visibility='onchange')



